﻿
namespace Basket.API.Data
{
    public class CachedBasketRepository(IBasketRepository repository
        , IDistributedCache cache) : IBasketRepository
    {
        public async Task<bool> DeleteBasketAsync(string userName, CancellationToken cancellationToken = default)
        {
            await repository.DeleteBasketAsync(userName, cancellationToken);
            await cache.RemoveAsync(userName);
            return true;
        }

        public async Task<ShoppingCart> GetBasketAsync(string userName, CancellationToken cancellationToken = default)
        {
            var basketJson = await cache.GetStringAsync(userName, cancellationToken);
            if (!string.IsNullOrEmpty(basketJson))
            {
                return JsonConvert.DeserializeObject<ShoppingCart>(basketJson)!;
            }
            var basket = await repository.GetBasketAsync(userName, cancellationToken);
            if (basket != null)
            {
                await cache.SetStringAsync(userName, JsonConvert.SerializeObject(basket), cancellationToken);
            }
            return basket!;
        }

        public Task<ShoppingCart> UpdateBasketAsync(ShoppingCart basket, CancellationToken cancellationToken = default)
        {
            repository.UpdateBasketAsync(basket, cancellationToken);
            cache.SetStringAsync(basket.UserName, JsonConvert.SerializeObject(basket), cancellationToken);
            return Task.FromResult(basket);
        }
    }
}
